package util;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	
	
	
	@SuppressWarnings("unchecked")
	public static <T> T get(Class<T> c, int id) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		T t = (T) session.get(c, id);
		session.getTransaction().commit();
		return t;
	}
	
	public static <T> T insert(T t) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(t);
		session.getTransaction().commit();
		return t;
	}
	
	public static <T> T update(T t) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.merge(t);
		session.getTransaction().commit();
		return t;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T delete(Class<T> c, int id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		T t = (T) session.load(c, id);
		if(null != t) {
			session.delete(t);
		}
		session.getTransaction().commit();
		return t;
	}

	public static <T> List<T> list(String query) {
		return list(query, null);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List<T> list(String query, Dictionary<String, Object> parameters) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<T> items = null;
		try {
			
			Query queryObject = session.createQuery(query);
			
			if (null != parameters)
			{
				Enumeration e = parameters.keys();
				 
			    while(e.hasMoreElements())
			    {
			    	Object key = e.nextElement();
					queryObject.setParameter(key.toString(), parameters.get(key));
			    }
			}
			items = (List<T>)queryObject.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return items;
	}
	
}
